package com.mc.jf.handler;

import com.alibaba.fastjson.JSON;
import com.mc.jf.entity.ResUtil;
import com.mc.jf.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {


        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest")) {
            WebUtils.renderString(response, JSON.toJSONString(ResUtil.error(HttpStatus.UNAUTHORIZED.value(),"登录验证失败")));
        } else {
            response.sendRedirect("/login");
        }

    }
}
